package com.five.matebook.activity.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;

import java.io.File;

public class DbHelper extends SQLiteOpenHelper {
    private static final String TAG = DbHelper.class.getSimpleName();

    private static String sDbName;

    private String mRealDbName;
    private DbHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mRealDbName = name;
    }

    private static volatile DbHelper sInstance;

    public static DbHelper getInstance(Context context) {
        if (sInstance == null)
            synchronized (DbHelper.class) {
                if (sInstance == null) {
                    sInstance = new DbHelper(context, sDbName, null, 1);
                }
            }
        return sInstance;
    }

    public static void doClose() {
        synchronized (DbHelper.class) {
            if (sInstance != null) {
                sInstance.close();
            }
            sInstance = null;
        }
    }

    public static void setsDbName(Context context, String name) {
        synchronized (DbHelper.class) {
            if (TextUtils.isEmpty(name)) {
                Log.e(TAG, "failed to set db name to " + name);
                return;
            }
            if (name.equals(sDbName)) {
                Log.w(TAG, "db name dosen't change");
                return;
            }
            sDbName = name;
            if (sInstance != null) {
                sInstance.close();
            }
            sInstance = null;
            getInstance(context);
        }
    }

    private volatile SQLiteDatabase mDb;

    public SQLiteDatabase getDb() {
        synchronized (this) {
            if (mDb == null) {
                mDb = this.getWritableDatabase();
            }
        }
        return mDb;
    }

    public static File getDbDir(Context context) {
        return context.getDatabasePath("test.db").getParentFile();
    }

    public File getDbFile(Context context) {
        return context.getDatabasePath(mRealDbName).getAbsoluteFile();
    }

    public static File getDbFile(Context context, String dbName) {
        return context.getDatabasePath(dbName).getAbsoluteFile();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
